package com.demo.wormhole.core.context;

import org.apache.commons.lang3.StringUtils;

/**
 * 上下文处理类
 */
public class WormholeContextHolder {
    private static final InheritableThreadLocal<WormholeContext> wormholeContextThreadLocal = new InheritableThreadLocal<>();
    
    /**
     * 链路穿透上下文标识
     */
    public static final String WORMHOLE_REQUEST_MARK = "X-Wormhole-Header-Request";
    
    /**
     * 获取上下文
     *
     * @return
     */
    public static WormholeContext getContext() {
        return wormholeContextThreadLocal.get();
    }
    
    /**
     * 获取上下文中的属性
     *
     * @param key
     * @return
     */
    public static String getProperty(String key) {
        WormholeContext wormholeContext = getContext();
        if (null != wormholeContext) {
            return wormholeContext.toString();
        }
        return null;
    }
    
    /**
     * 设置上下文
     *
     * @param context
     */
    public static void setContext(WormholeContext context) {
        wormholeContextThreadLocal.set(context);
    }
    
    public static void setContext(String contextStr) {
        if (StringUtils.isNotEmpty(contextStr)) {
            setContext(new WormholeContext(contextStr));
        }
    }
    
    /**
     * 将上下文进行失效
     */
    public static void invalidContext() {
        wormholeContextThreadLocal.remove();
    }
    
}
